﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace Microsoft.WowAddonStudio.FrameXml.Serialization.Support
{
    public class PropertyBag : INotifyPropertyChanged
    {
        private readonly Dictionary<string, object> defaultValues = new Dictionary<string, object>();
        private readonly Dictionary<string, object> values = new Dictionary<string, object>();
        private readonly object owner;

        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyBag"/> class.
        /// </summary>
        /// <param name="owner">The owner of the property bag.</param>
        public PropertyBag(object owner)
        {
            if (owner == null)
                throw new ArgumentNullException("owner");

            this.owner = owner;

            // Enable inheritance by default
            InheritanceEnabled = true;
        }

        /// <summary>
        /// Gets or sets a value indicating whether inheritance is enabled.
        /// </summary>
        public bool InheritanceEnabled { get; set; }

        /// <summary>
        /// Gets or sets the inherited property bag.
        /// </summary>
        public PropertyBag InheritedPropertyBag { get; set; }

        /// <summary>
        /// Gets or sets the value of a property.
        /// </summary>
        /// <param name="propertyName">The name of the property.</param>
        public object this[string propertyName]
        {
            get { return GetValue<object>(propertyName); }
            set { SetValue(propertyName, value); }
        }

        /// <summary>
        /// Gets the value of a property.
        /// </summary>
        /// <typeparam name="T">The type of the property.</typeparam>
        /// <param name="propertyName">The name of the property.</param>
        /// <returns>The value of the property.</returns>
        public T GetValue<T>(string propertyName)
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            // See if property bag contains a value for the property
            if (values.ContainsKey(propertyName))
                return (T)values[propertyName];

            // If property bag inherits from another property bag and inheritance enabled, delegate GetValue
            if (InheritedPropertyBag != null && InheritanceEnabled)
                return InheritedPropertyBag.GetValue<T>(propertyName);

            // Return the default value for the property
            return GetDefaultValue<T>(propertyName);
        }

        /// <summary>
        /// Sets the value of a property.
        /// </summary>
        /// <typeparam name="T">The type of the property.</typeparam>
        /// <param name="propertyName">The name of the property.</param>
        /// <param name="value">The value of the property.</param>
        public void SetValue<T>(string propertyName, T value)
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            // Raise PropertyChangingEventArgs and RaiseInheritedPropertyChanging event
            RaisePropertyChanging(new PropertyChangingEventArgs(propertyName));

            // If value is the default value, reset the property

            if (!this.HasInheritedValue(propertyName) && Object.Equals(value, GetDefaultValue<object>(propertyName)))
            {
                ResetValue(propertyName);
            }

            if (this.HasInheritedValue(propertyName) && Object.Equals(value, GetInheritedValue<object>(propertyName)))
            {
                ResetValue(propertyName);
            }
            else
            {
                // Ordinary value, set the property value
                values[propertyName] = value;
            }

            // Raise PropertyValueChanged event
            RaisePropertyChanged(new PropertyChangedEventArgs(propertyName));
        }

        /// <summary>
        /// Checks whether a property has an inherited value.
        /// </summary>
        /// <param name="propertyName">The name of the property.</param>
        /// <returns>True, if the property has an inherited value; false otherwise.</returns>
        private bool HasOnlyInheritedValue(string propertyName)
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            if (InheritedPropertyBag != null)
                return (InheritedPropertyBag.HasValue(propertyName)
                        || InheritedPropertyBag.HasInheritedValue(propertyName));

            return values.ContainsKey(propertyName);
        }

        /// <summary>
        /// Checks whether a property has a value specified.
        /// </summary>
        /// <param name="propertyName">The name of the property.</param>
        /// <returns>True, if the property has a value; false otherwise.</returns>
        public bool HasValue(string propertyName)
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            return values.ContainsKey(propertyName);
        }

        /// <summary>
        /// Checks whether a property has an inherited value.
        /// </summary>
        /// <param name="propertyName">The name of the property.</param>
        /// <returns>True, if the property has an inherited value; false otherwise.</returns>
        public bool HasInheritedValue(string propertyName)
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            if (InheritedPropertyBag != null)
            {
                return (InheritedPropertyBag.HasValue(propertyName) ||
                        InheritedPropertyBag.HasInheritedValue(propertyName));
            }

            return false;
        }

        /// <summary>
        /// Gets the inherited value.
        /// </summary>
        /// <typeparam name="T">The type of the value.</typeparam>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns></returns>
        public T GetInheritedValue<T>(string propertyName)
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");
            if (InheritedPropertyBag == null)
                throw new InvalidOperationException("Object does not inherit from another object.");

            return InheritedPropertyBag.GetValue<T>(propertyName);
        }

        /// <summary>
        /// Resets the value of a property.
        /// </summary>
        /// <param name="propertyName">The name of the property.</param>
        public void ResetValue(string propertyName)
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            if (values.ContainsKey(propertyName))
            {
                // Raise PropertyValueChanging event
                RaisePropertyChanging(new PropertyChangingEventArgs(propertyName));

                values.Remove(propertyName);

                // Raise PropertyValueChanged event
                RaisePropertyChanged(new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Gets the default value of a property.
        /// </summary>
        /// <typeparam name="T">The type of the valeu.</typeparam>
        /// <param name="propertyName">The name of the property.</param>
        /// <returns>The default value of the property.</returns>
        public T GetDefaultValue<T>(string propertyName)
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            // TODO: Make this static

            // See if default value is already cached
            if (defaultValues.ContainsKey(propertyName))
                return (T)defaultValues[propertyName];

            // Look up property info and look for [DefaultValue(...)]
            PropertyInfo propertyInfo = owner.GetType().GetProperty(propertyName);
            if (propertyInfo != null)
            {
                var defaultValueAttribute = propertyInfo.GetCustomAttributes(typeof(DefaultValueAttribute), true)
                                                        .OfType<DefaultValueAttribute>()
                                                        .SingleOrDefault();

                if (defaultValueAttribute != null)
                {
                    // Store default value in dictionary
                    defaultValues[propertyName] = defaultValueAttribute.Value;
                }
            }

            // If we found no default value, default(T) will be the default
            if (!defaultValues.ContainsKey(propertyName))
                defaultValues[propertyName] = default(T);

            return (T)defaultValues[propertyName];
        }

        /// <summary>
        /// Gets the inherited elements.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns></returns>
        public InheritableList<T> GetInheritedElements<T>(string propertyName) where T : SerializationObject
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            if (InheritedPropertyBag != null && InheritanceEnabled)
                return InheritedPropertyBag.GetInheritableList<T>(propertyName);

            return null;
        }

        /// <summary>
        /// Gets the inherited elements.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TInheritableList">The type of the inheritable list.</typeparam>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns></returns>
        public TInheritableList GetInheritedElements<T, TInheritableList>(string propertyName)
            where TInheritableList : InheritableList<T>
            where T : SerializationObject
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            if (InheritedPropertyBag != null && InheritanceEnabled)
                return InheritedPropertyBag.GetInheritableList<T, TInheritableList>(propertyName);

            return null;
        }

        /// <summary>
        /// Gets an inheritable list for a property.
        /// </summary>
        /// <typeparam name="T">The type of the property.</typeparam>
        /// <param name="propertyName">The name of the property.</param>
        /// <returns>An instance of the <see cref="InheritableList{T}"/> class that supports collection inheritance.</returns>
        public InheritableList<T> GetInheritableList<T>(string propertyName) where T : SerializationObject
        {
            if (propertyName == null)
                throw new ArgumentNullException("propertyName");

            // Create it if it has not been created yet
            if (!values.ContainsKey(propertyName))
                values[propertyName] = new InheritableList<T>(this, propertyName);

            var inheritableList = (InheritableList<T>) values[propertyName];

            // Do not serialize empty lists
            if (!InheritanceEnabled && inheritableList.Count == 0)
                return null;

            return inheritableList;
        }

        /// <summary>
        /// Gets the inheritable list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TInheritableList">The type of the inheritable list.</typeparam>
        /// <param name="propertyName">Name of the property.</param>
        /// <returns></returns>
        public TInheritableList GetInheritableList<T, TInheritableList>(string propertyName)
            where TInheritableList : InheritableList<T>
            where T : SerializationObject
        {
            // Create it if it has not been created yet
            if (!values.ContainsKey(propertyName))
                values[propertyName] = Activator.CreateInstance(typeof(TInheritableList), this, propertyName);

            var inheritableList = (TInheritableList) values[propertyName];

            // Return null when inheritance is disabled and no items are available (do not serialize empty list)
            if (!InheritanceEnabled && inheritableList.Count == 0)
                return null;

            return inheritableList;
        }

        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// Occurs when [property changing].
        /// </summary>
        public event PropertyChangingEventHandler PropertyChanging;


        protected event EventHandler<InheritedPropertyChangingEventArgs> inheritedPropertyChanging;

        /// <summary>
        /// Occurs when [inherited property changing].
        /// </summary>
        protected event EventHandler<InheritedPropertyChangingEventArgs> InheritedPropertyChanging
        {
            add { inheritedPropertyChanging += value; }
            remove { inheritedPropertyChanging -= value; }
        }

        /// <summary>
        /// Unregister inherited property changing listeners.
        /// </summary>
        protected void UnRegisterInheritedPropertyChangingListeners()
        {
            inheritedPropertyChanging = null;
        }

        /// <summary>
        /// Raises the inherited property changing.
        /// </summary>
        /// <param name="e">The <see cref="Microsoft.WowAddonStudio.FrameXml.Serialization.Support.InheritedPropertyChangingEventArgs"/> instance containing the event data.</param>
        private void RaiseInheritedPropertyChanging(InheritedPropertyChangingEventArgs e)
        {
            if (inheritedPropertyChanging != null)
                inheritedPropertyChanging(this, e);
        }


        /// <summary>
        /// Raises the property changing.
        /// </summary>
        /// <param name="e">The <see cref="System.ComponentModel.PropertyChangingEventArgs"/> instance containing the event data.</param>
        private void RaisePropertyChanging(PropertyChangingEventArgs e)
        {
            if (PropertyChanging != null)
                PropertyChanging(this, e);
        }

        /// <summary>
        /// Raises the property changed.
        /// </summary>
        /// <param name="e">The <see cref="System.ComponentModel.PropertyChangedEventArgs"/> instance containing the event data.</param>
        private void RaisePropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }
    }
}